package com.acoreful.ackitcloud.filter;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http访问日志
 * 开启则打印请求路径、方式、Header、HttpStatus，其他详细信息各微服务打印
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class HttpAccessLogFilter implements GlobalFilter, Ordered {
    
    @Value("${gateway.config.httpAccessLog.enabled:false}")
    private boolean logEnable;
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if(!logEnable){
            return chain.filter(exchange);
        }
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        StopWatch stopWatch=new StopWatch();
        stopWatch.start("gateway-biz-handle");
        return chain.filter(exchange).then(Mono.fromRunnable(()->{
            try{
                MDC.setContextMap(contextMap);
                this.printLog(exchange,stopWatch);
            }finally {
                MDC.clear();
            }
        }));
    }

    /**
     * 打印日志
     * @param exchange
     * @param stopWatch
     */
    private void printLog(ServerWebExchange exchange,StopWatch stopWatch){
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        String requestMethod = exchange.getRequest().getMethod().name();
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        ServerHttpResponse response = exchange.getResponse();
        stopWatch.stop();
        StringBuilder detail = new StringBuilder(300);
        List<Object> args = new ArrayList<>();
        if (route != null) {
            detail.append("routeId:{} ");
            args.add(route.getId());
        }
        detail.append("{}: {} {} 耗时:{} ms\nHeaders: ");
        args.add(requestMethod);
        args.add(requestUrl);
        args.add(response.getStatusCode().value());
        args.add(stopWatch.getTotalTimeMillis());
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        headers.forEach((headerName, headerValue) -> {
            detail.append("{}={}&");
            args.add(headerName);
            args.add(headerValue);
        });
        log.info( StrUtil.removeSuffix(detail, "&") + StrPool.LF, args.toArray());
    }
    
    @Override
    public int getOrder() {
        return -200;
    }
    
}